package com.mingqijia.gassafety.webserver.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.WarningAlarm;
import com.mingqijia.gassafety.db.mapper.WarningAlarmMapper;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.webserver.dto.CallTaskDTO;
import com.mingqijia.gassafety.webserver.service.AicallTaskService;
import com.mingqijia.gassafety.webserver.service.CallTaskService;
import com.mingqijia.gassafety.webserver.service.EquipmentService;
import com.mingqijia.gassafety.webserver.service.WarningRecordService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName CallTaskServiceImpl.java
 * @Description 呼叫任务
 * @createTime 2023年02月13日
 */
@Service
@Slf4j
public class CallTaskServiceImpl implements CallTaskService {

    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    XFCallServiceImpl xFCallService;
    @Autowired
    EquipmentServiceImpl equipmentService;
    @Autowired
    WarningAlarmMapper warningAlarmMapper;
    @Autowired
    WarningRecordService recordService;
    @Autowired
    AicallTaskService aicallTaskService;

    private static final long validTime = 600L;


    @Override
    public void callTask(Long id,String operatorBy) {
        log.info("子线程开始执行手动呼叫任务......" + System.currentTimeMillis());
        log.info("callTask-外呼入参：{}", JSONObject.toJSONString(id));
        //不存在则加锁成功
        String callId = String.valueOf(id);
        try {
            Boolean flag = redisUtil.setIfAbsent(callId, id, validTime);
            if (flag) {
                callTaskDetail(id,operatorBy);
            }
            redisUtil.del(callId);
            log.info("子线程结束执行外呼任务......" + System.currentTimeMillis());
        } catch (Exception e) {
            redisUtil.del(callId);
            log.info("callTask异常：{}", e.getStackTrace());
            throw new BizException("外呼失败！");
        }
    }

    private void callTaskDetail(Long id,String operatorBy) {
        WarningAlarm warningAlarm = warningAlarmMapper.selectById(id);
        if (warningAlarm == null) return;
        String pushLevels = warningAlarm.getPushLevels();
        String pushPhones = warningAlarm.getPushPhones();
        String pushStaffs = warningAlarm.getPushStaffs();
        Map<String, Integer> objectTypeMap = new HashMap<>();
        Set<String> phones = new HashSet<>();
        getPhones(pushLevels, phones,objectTypeMap,0);
        getPhones(pushPhones, phones,objectTypeMap,3);
        getPhones(pushStaffs, phones,objectTypeMap,1);
        log.info("callTaskDetail-phones:{}", JSONObject.toJSONString(phones));
        String spId = warningAlarm.getSpId();
        String imei = warningAlarm.getIMEI();


        Map<String, Object> map = sendCallTask(spId, phones, imei);
        if (map.isEmpty()) {
            log.error("callTaskDetail-map:{}", JSONObject.toJSONString(map));
            warningAlarm.setDisposeStatus(0);
            warningAlarm.setDisposeTime("");
            warningAlarmMapper.updateById(warningAlarm);
            throw new BizException("外呼异常,请联系管理员");
        }
        //数据存储
        recordService.saveCallList((JSONArray)map.get("data"),
                (Map<String, Object>)map.get("dtuInfos"), (List<String>) map.get("phoneList")
                , warningAlarm, warningAlarm.getSpId(),objectTypeMap,operatorBy,(String)map.get("robotContent"));
        log.info("callTaskDetail-手动呼叫结束!");
    }

    private Map<String, Object> sendCallTask(String spId, Set<String> phones, String imei) {
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> dtuInfos = equipmentService.selectByImei(imei,spId);
        log.info("sendCallTask-selectByImei:{}", JSONObject.toJSONString(dtuInfos));
        CallTaskDTO callTaskDTO = new CallTaskDTO();
        List<JSONArray> calls = new ArrayList<>();
        if (dtuInfos == null) return null;
        String address = "";
        Object position = dtuInfos.get("installationPosition");
        if (Integer.parseInt(dtuInfos.get("templateType") + "") == 2) {
            address = dtuInfos.get("address") + "";
        } else {
            address = dtuInfos.get("custAddress") + "";
        }
        if (!StringUtils.isEmpty(address)) {
            address = "地址是在" + address;
            if (!StringUtils.isEmpty(position)) address = address + "(" + position + ")";
        }else {
            address="";
        }
        List<String> phoneList = new ArrayList<>();
        phones.forEach(s -> {
            phoneList.add(s);
        });
        dtuInfos.put("addressCopy",address);

        Object factoryName = "";
        callTaskDTO = aicallTaskService.getAicallTaskByType(null, spId);
        boolean hasFactoryName = false;
        if ( null!=callTaskDTO.getRobotContent() && callTaskDTO.getRobotContent().contains("#factoryName#") ){
            factoryName = equipmentService.getEquipmentManufacturerName(
                    null==dtuInfos.get("equipmentManufacturer")?"":dtuInfos.get("equipmentManufacturer").toString(),
                    spId
            );
            dtuInfos.put("factoryName",factoryName);
            callTaskDTO.getCallColumn().add("厂家名称");
            hasFactoryName = true;
        }

        for (String phone : phoneList) {
            if (phone.contains("-"))phone = phone.replace("-", "");
            JSONArray array = new JSONArray();
            array.add(0, phone);
            array.add(1, address);
            array.add(2, dtuInfos.get("name"));
            array.add(3, dtuInfos.get("paramValue"));
            if( hasFactoryName ){
                array.add(array.size(), factoryName);
            }
            calls.add(array);
        }
        callTaskDTO.setCallList(calls);
        JSONObject jsonObject = xFCallService.callPoolCreate(callTaskDTO,spId);
        log.info("callTaskDetail-callCreate:{}", JSONObject.toJSONString(jsonObject));
        if (jsonObject == null ) return null;
        JSONArray data = jsonObject.getJSONArray("call_ids");
        log.info("callTaskDetail-saveCallList:dtuInfos:{},data:{},spid:{}" +
                        "", JSONObject.toJSONString(dtuInfos)
                , JSONObject.toJSONString(data), JSONObject.toJSONString(spId));
        
        res.put("robotContent",callTaskDTO.getRobotContent());
        res.put("data", data);
        res.put("dtuInfos", dtuInfos);
        res.put("phoneList", phoneList);
        return res;
    }


    private void getPhones(String pushLevels, Set<String> phones,Map<String, Integer> objectTypeMap,
                           int type ) {
        if (!StringUtils.isEmpty(pushLevels)
                && pushLevels.contains(WarningDataServiceImpl.split_f)) {
            String[] split = pushLevels.split(WarningDataServiceImpl.split_f);
            for (String s : split) {
                phones.add(s);
                objectTypeMap.put(s,type);
            }
        }
    }
}